using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos;
using Work.ErrorCode;

namespace Work.API.Controllers
{
    /// <summary>
    /// 病历管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MedicalRecordController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<MedicalRecordController> _logger;

        public MedicalRecordController(IMediator mediator, ILogger<MedicalRecordController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 创建或更新病历
        /// </summary>
        /// <param name="request">病历信息</param>
        /// <returns>病历ID</returns>
        [HttpPost]
        public async Task<ApiResult<int>> CreateOrUpdate(CreateMedicalRecordCommand request)
        {
            try
            {
                return await _mediator.Send(request);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "创建病历失败");
                return new ApiResult<int>
                {
                    Code = ApiEnum.失败,
                    Message = $"创建病历失败：{ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 根据预约ID获取病历
        /// </summary>
        /// <param name="appointmentId">预约ID</param>
        /// <returns>病历信息</returns>
        [HttpGet]
        public async Task<ApiResult<MedicalRecordDto?>> GetByAppointmentId(int appointmentId)
        {
            try
            {
                var query = new GetMedicalRecordByAppointmentQuery
                {
                    AppointmentId = appointmentId
                };
                return await _mediator.Send(query);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "查询病历失败");
                return new ApiResult<MedicalRecordDto?>
                {
                    Code = ApiEnum.失败,
                    Message = $"查询病历失败：{ex.Message}",
                    Data = null
                };
            }
        }
    }
}








